/*
    Copyright 2010 Barnet Wagman

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
 */

package com.norbl.util;
import java.util.*;

/**
 *
 * @author Barnet Wagman
 */
public class Counter extends HashMap<String,Long>
        implements java.io.Serializable {
        static final long serialVersionUID = 0L;

    public static Counter staticCounter;    
        
    HashMap<String,Long> ht;
    
    public Counter() { super(); }
        
    synchronized public void inc(String name) {
        Long cnt = get(name);
        if ( cnt == null) {
            cnt = new Long(0);
            put(name,cnt);
        }
        cnt = new Long(cnt.intValue() + 1);
        put(name,cnt);
    }
    
    public void add(String name,int n) { add(name,(long) n); }
    
    public void set(String name, long n) {
        put(name,new Long(n));
    }
    
    synchronized public void add(String name,long n) {
        Long cnt = get(name);
        if ( cnt == null) {
            cnt = new Long(0L);
            put(name,cnt);
        }
        cnt = new Long(cnt.intValue() + n);
        put(name,cnt);
    }
    
    synchronized public long getCount(String name) {
        Long n = this.get(name);
        if ( n == null ) return(0L);
        else return(n.longValue());
    }        
    
    public long getTotalOfCounts() {

        int n = 0; 
        for ( Iterator<Long> it = ht.values().iterator(); it.hasNext(); ) {
            n += it.next().intValue();
        }
        return(n);
    }

    public void add(Counter other) {
        if ( other == null ) return;
        for ( Iterator<String> it = other.keySet().iterator(); it.hasNext(); ) {
            String k = it.next();
            long n = other.getCount(k);
            this.add(k, n);
        }
    }
    
        // ------------------------------------------------
    
    public static void addStatic(String name, long n) {
        if ( staticCounter == null ) staticCounter = new Counter();
        staticCounter.add(name,n);
    }
  
    class NameCount implements Comparable {
        String name;
        int n;

        NameCount(String name, int n) {
            this.name = name;
            this.n = n;
        }

        public int compareTo(Object other) {
            return( name.compareTo( ((NameCount) other).name ) );
        }
    }
}
